import { Response } from 'express';
import { AuthenticatedRequest } from '../types/auth';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';
import { StatisticsService } from '../services/statisticsService';
import { logger } from '../utils/logger';

export const statisticsController = {
  // 获取全校成绩统计
  async getSchoolStatistics(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { schoolId } = req.params;
      const statistics = await StatisticsService.getSchoolStatistics(schoolId);

      res.json({
        success: true,
        data: statistics
      });
    } catch (error) {
      logger.error('获取全校成绩统计失败', {
        context: 'statisticsController.getSchoolStatistics',
        error
      });
      throw error;
    }
  },

  // 获取班级成绩对比
  async getClassComparison(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { schoolId } = req.params;
      const { classIds } = req.query;

      // 如果提供了特定的班级ID列表，则进行过滤
      const filterClassIds = classIds ? String(classIds).split(',') : undefined;

      const comparison = await StatisticsService.getClassComparison(schoolId);

      // 如果有班级过滤，应用过滤
      if (filterClassIds) {
        const filteredData = {
          ...comparison,
          classRankings: comparison.classRankings.filter(
            (c: any) => filterClassIds.includes(c.class_id)
          ),
          classDistributions: comparison.classDistributions.filter(
            (d: any) => filterClassIds.includes(d.class_id)
          )
        };
        return res.json({
          success: true,
          data: filteredData
        });
      }

      res.json({
        success: true,
        data: comparison
      });
    } catch (error) {
      logger.error('获取班级成绩对比失败', {
        context: 'statisticsController.getClassComparison',
        error
      });
      throw error;
    }
  },

  // 获取年级成绩对比
  async getGradeComparison(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { schoolId } = req.params;
      const { grades } = req.query;

      // 如果提供了特定的年级列表，则进行过滤
      const filterGrades = grades ? String(grades).split(',').map(Number) : undefined;

      const comparison = await StatisticsService.getGradeComparison(schoolId);

      // 如果有年级过滤，应用过滤
      if (filterGrades) {
        const filteredData = {
          gradeAverages: comparison.gradeAverages.filter(
            (g: any) => filterGrades.includes(g.grade)
          ),
          gradePassRates: comparison.gradePassRates.filter(
            (g: any) => filterGrades.includes(g.grade)
          )
        };
        return res.json({
          success: true,
          data: filteredData
        });
      }

      res.json({
        success: true,
        data: comparison
      });
    } catch (error) {
      logger.error('获取年级成绩对比失败', {
        context: 'statisticsController.getGradeComparison',
        error
      });
      throw error;
    }
  }
};
